package cn.tedu.ivos2.dictoption.service.impl;

import cn.tedu.ivos2.base.exception.ServiceException;
import cn.tedu.ivos2.base.response.StatusCode;
import cn.tedu.ivos2.dict.mapper.DictMapper;
import cn.tedu.ivos2.dict.pojo.dto.DictQuery;
import cn.tedu.ivos2.dict.pojo.vo.DictVO;
import cn.tedu.ivos2.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos2.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos2.dictoption.pojo.entity.DictOption;
import cn.tedu.ivos2.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivos2.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    private DictOptionMapper dictOptionMapper;
    @Autowired
    private DictMapper dictMapper;

    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery dictOption) {
        log.debug("查询字典项业务：dictOptionQuery={}", dictOption);
        List<DictOptionVO> list = dictOptionMapper.selectDictOption(dictOption);
        return list;
    }

    @Override
    public void saveDictOption(DictOptionQuery dictOptionQuery) {
        log.debug("保存字典项业务：dictOptionQuery={}", dictOptionQuery);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionQuery,dictOption);
        if (dictOption.getId()==null){
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        }else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }

    }

    @Override
    public void deleteDictOption(Long id) {
        log.debug("删除字典项业务：id={}", id);
        dictOptionMapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> DictVOList = dictMapper.selectDict(dictQuery);
        if(DictVOList!=null && DictVOList.size()>0){
            DictVO dictVO = DictVOList.get(0);
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.selectDictOption(dictOptionQuery);
            return dictOptionVOList;
        }else{
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }
}
